using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using netcore_comm.Nlog;
using netcore_service.IService;
using netcore_service.Model;


//[Authorize]
public class ChatHub : Hub
{
    private readonly IChatService _chatService;
    private readonly IUserConnectionManager _userConnectionManager;
    private readonly INLogHelper _logger;

    public ChatHub(IChatService chatService, IUserConnectionManager userConnectionManager, INLogHelper logger)
    {
        _chatService = chatService;
        _userConnectionManager = userConnectionManager;
        _logger = logger;
    }

    public override async Task OnConnectedAsync()
    {
        _logger.Info($"Client connected: {Context.ConnectionId}");
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        await _userConnectionManager.RemoveConnection(Context.ConnectionId);
        _logger.Info($"Client disconnected: {Context.ConnectionId}");
        await base.OnDisconnectedAsync(exception);
    }

    // 客户连接
    public async Task CustomerConnect(string customerId, string school)
    {
        await _userConnectionManager.AddConnection(customerId, Context.ConnectionId, UserRole.Customer, school);
        await Groups.AddToGroupAsync(Context.ConnectionId, $"customer_{customerId}");

        _logger.Info($"Customer {customerId} connected");
    }

    // 客服连接
    public async Task AgentConnect(string agentId, string school)
    {
        await _userConnectionManager.AddConnection(agentId, Context.ConnectionId, UserRole.Agent, school);
        await Groups.AddToGroupAsync(Context.ConnectionId, $"agent_{agentId}");

        // 获取等待中的会话并通知客服
        var waitingSessions = await _chatService.GetWaitingSessionsAsync(school);
        await Clients.Group($"agent_{agentId}").SendAsync("WaitingSessionsUpdated", waitingSessions);

        _logger.Info($"Agent {agentId} connected");
    }

    // 创建新会话
    public async Task<string> CreateSession(string customerId, string customerName, string school, string schoolName, string logo, string? initialMessage = null)
    {
        try
        {
            var session = await _chatService.CreateSessionAsync(customerId, customerName, school, schoolName, logo, initialMessage);

            // 通知所有在线客服
            var onlineAgents = await _userConnectionManager.GetOnlineAgents(school);
            foreach (var agentId in onlineAgents)
            {
                await Clients.Group($"agent_{agentId}").SendAsync("NewSessionCreated", session);
            }

            // 将客户加入会话组
            await Groups.AddToGroupAsync(Context.ConnectionId, $"session_{session.Id}");

            return session.Id;
        }
        catch (Exception ex)
        {
            _logger.Error(ex + "Error creating session");
            throw new HubException("Failed to create session");
        }
    }

    // 客服接受会话
    public async Task<bool> AcceptSession(string sessionId, string agentId, string agrntName, string school)
    {
        try
        {
            var session = await _chatService.AcceptSessionAsync(sessionId, agentId, agrntName, school);
            if (session == null) return false;

            // 将客服加入会话组
            await Groups.AddToGroupAsync(Context.ConnectionId, $"session_{sessionId}");

            // 通知客户
            await Clients.Group($"customer_{session.CustomerId}")
                .SendAsync("SessionAccepted", new { agentId, agentName = agrntName });

            // 通知其他客服更新会话列表
            var waitingSessions = await _chatService.GetWaitingSessionsAsync(school);
            var onlineAgents = await _userConnectionManager.GetOnlineAgents(school);
            foreach (var onlineAgentId in onlineAgents)
            {
                await Clients.Group($"agent_{onlineAgentId}").SendAsync("WaitingSessionsUpdated", waitingSessions);
            }

            return true;
        }
        catch (Exception ex)
        {
            _logger.Error(ex + "Error accepting session");
            return false;
        }
    }

    // 发送消息
    public async Task SendMessage(string sessionId, string senderId, string senderName, string Logo, string content)
    {
        try
        {
            var message = await _chatService.SendMessageAsync(sessionId, senderId, senderName, Logo, content);

            // 获取消息的完整信息（包括发送者）
            var fullMessage = await _chatService.GetSessionMessagesAsync(sessionId);
            var latestMessage = fullMessage.First();

            var messageDto = new MessageDto
            {
                Id = latestMessage.Id,
                SessionId = latestMessage.SessionId,
                SenderId = latestMessage.SenderId,
                SenderName = latestMessage.SenderName,
                Content = latestMessage.Content,
                Logo = latestMessage.Logo,
                MessageType = latestMessage.MessageType,
                SentAt = latestMessage.SentAt,
                IsRead = latestMessage.IsRead
            };

            // 发送给会话组中的所有用户
            await Clients.Group($"session_{sessionId}").SendAsync("ReceiveMessage", messageDto);

            // 更新会话列表
            await UpdateSessionList(sessionId);
        }
        catch (Exception ex)
        {
            _logger.Error(ex + "Error sending message");
            throw new HubException("Failed to send message");
        }
    }

    // 标记消息为已读
    public async Task MarkAsRead(string sessionId, string userId)
    {
        await _chatService.MarkMessagesAsReadAsync(sessionId, userId);
        await Clients.Group($"session_{sessionId}").SendAsync("MessagesRead", new { sessionId, userId });
    }

    private async Task UpdateSessionList(string sessionId)
    {
        var session = await _chatService.GetUserSessionsAsync(sessionId);
        // 通知相关用户更新会话列表
        // 这里需要根据具体业务逻辑实现
    }


    public async Task<ApiResult<ChatSession>> UserSessionsByCustomer(string userId)
    {
        return APIResult.GetSuccess(await _chatService.GetUserSessionsByCustomer(userId));
    }

    public async Task<ApiResult<List<Message>>> SessionMessages(string sessionId, int count)
    {
        return APIResult.GetSuccess(await _chatService.GetSessionMessagesAsync(sessionId, count));
    }

    public async Task<ApiResult<List<ChatSession>>> UserSessionsBySchool(string school)
    {
        return APIResult.GetSuccess(await _chatService.GetScoolSessionsAsync(school));
    }

    public async Task<ApiResult<List<ChatSession>>> SchoolSessionsByCustomer(string userId)
    {
        return APIResult.GetSuccess(await _chatService.SchoolSessionsByCustomer(userId));
    }
}